package com.oa.hyperion.core.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.hyperion.entity.User;

import com.oa.hyperion.exception.http.ForbiddenException;
import com.oa.hyperion.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserLoginRealm  extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //转换成SysUserPasswordToken
        UsernamePasswordToken sysUserPasswordToken = (UsernamePasswordToken) authenticationToken;
        //获取用户名
        String username = sysUserPasswordToken.getPrincipal().toString();
        //是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account",username);
        User user = userService.getOne(wrapper);
        //用户不存在
        if(user==null){
            throw new ForbiddenException(50001);
        }
        //用户被锁定
        if(!user.getStatus().equals("y")){
            throw new ForbiddenException(50005);
        }
        //设置盐值
        ByteSource byteSource = ByteSource.Util.bytes(username);
        //密码和用户名进行验证
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),byteSource,getName());
        return simpleAuthenticationInfo;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
